<template>
  <view class="login-container">
    <!-- 顶部logo -->
    <view class="logo">
      <image src="/static/logo.png" mode="widthFix"></image>
      <view class="welcome-text">
        <text class="line1">欢迎来到</text>
        <text class="line2">你的生活旅游助手</text>
      </view>
    </view>
    
    <!-- 登录方式切换 -->
    <view class="login-tab">
      <view 
        class="tab-item" 
        :class="{'active': loginType === 'password'}" 
        @click="loginType = 'password'"
      >
        密码登录
      </view>
      <view 
        class="tab-item" 
        :class="{'active': loginType === 'sms'}" 
        @click="loginType = 'sms'"
      >
        验证码登录
      </view>
    </view>
    
    <!-- 登录表单 -->
    <view class="login-form">
      <view class="form-item">
        <input 
          type="number" 
          v-model="form.phonenumber" 
          placeholder="请输入手机号"
          maxlength="11"
        />
      </view>
      
      <!-- 密码登录输入框 -->
      <view class="form-item" v-if="loginType === 'password'">
        <input 
          type="password" 
          v-model="form.password" 
          placeholder="请输入密码"
          password
        />
      </view>
      
      <!-- 验证码登录输入框 -->
      <view class="form-item sms-form-item" v-if="loginType === 'sms'">
        <input 
          type="number" 
          v-model="form.code" 
          placeholder="请输入验证码"
          maxlength="6"
        />
        <button 
          class="sms-btn" 
          :disabled="isSending || countdown > 0"
          @click="handleSendSmsCode"
        >
          {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
        </button>
      </view>
      
      <!-- 登录/注册按钮 -->
      <view class="btn-group">
        <button class="btn-login" @click="handleLogin">
          {{ loginType === 'password' ? '登录' : '验证码登录' }}
        </button>
      </view>
      
      <!-- 微信登录 -->
      <view class="wechat-login">
        <view class="divider">
          <text>或</text>
        </view>
        <button 
          class="btn-wechat" 
          @click="handleWechatLogin"
        >
          <image src="/static/wechat.png" mode="aspectFit"></image>
          <text>微信登录</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { 
  loginByPassword, 
  registerByPassword, 
  loginByWechat,
  loginBySms,
  sendSmsCode
} from '@/api/auth'
import { useUserStore } from '@/store/modules/user'

// 初始化用户 store
const userStore = useUserStore()

// 登录方式：password-密码登录, sms-验证码登录
const loginType = ref('password')

// 短信验证码倒计时
const countdown = ref(0)
// 是否正在发送验证码
const isSending = ref(false)

// 表单数据
const form = reactive({
  phonenumber: '',
  password: '',
  code: ''
})

// 添加节流变量
const isWechatLogging = ref(false)

// 验证手机号
const validatePhone = () => {
  if (!form.phonenumber) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return false
  }
  
  if (!/^1[3-9]\d{9}$/.test(form.phonenumber)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 发送验证码
const handleSendSmsCode = async () => {
  if (isSending.value) return
  
  if (!validatePhone()) return
  
  try {
    isSending.value = true
    
    // 发送验证码请求
    const res = await sendSmsCode({ phonenumber: form.phonenumber })
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    // 提示用户
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    isSending.value = false
  }
}

// 登录处理
const handleLogin = async () => {
  try {
    // 表单验证
    if (!validatePhone()) return
    
    // 根据不同登录方式进行处理
    if (loginType.value === 'password') {
      // 密码登录方式
      if (!form.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      // 发起密码登录请求
      const res = await loginByPassword({
        phonenumber: form.phonenumber,
        password: form.password
      })
      
      // 处理登录成功
      handleLoginSuccess(res)
    } else {
      // 验证码登录方式
      if (!form.code) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      
      // 发起验证码登录请求
      const res = await loginBySms({
        phonenumber: form.phonenumber,
        code: form.code
      })
      
      // 处理登录成功
      handleLoginSuccess(res)
    }
  } catch (error) {
    console.error('登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none'
    })
  }
}

// 处理登录成功
const handleLoginSuccess = (res) => {
  console.log(res,'222222222222222');
  
  if(res.data){
    // 使用store管理用户登录状态
  userStore.setToken(res.data.accessToken)
  userStore.setUserInfo(res.data.user)
  userStore.setLoginStatus(true)
  }
  // 登录成功提示
  uni.showToast({
    title: '登录成功',
    icon: 'success'
  })
  
  // 跳转到首页
  setTimeout(() => {
    // 返回上一页，如果是从个人中心页面跳转来的
    uni.navigateBack({
      delta: 1,
      fail: () => {
        // 如果没有上一页，则跳转到发现页
        uni.switchTab({
          url: '/pages/discovery/index'
        })
      }
    })
  }, 1500)
}

// 手机号注册
const handleRegister = async () => {
  try {
    // 表单验证
    if (!validatePhone()) return
    
    if (!form.password) {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    
    if (form.password.length < 6) {
      uni.showToast({
        title: '密码长度不能小于6位',
        icon: 'none'
      })
      return
    }
    
    // 发起注册请求
    const res = await registerByPassword({
      phonenumber: form.phonenumber,
      password: form.password
    })
    
    // 处理登录成功
    handleLoginSuccess(res)
  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: error.message || '注册失败',
      icon: 'none'
    })
  }
}

// 微信登录
const handleWechatLogin = async () => {
  // 防止重复点击
  if (isWechatLogging.value) {
    uni.showToast({
      title: '登录中，请稍候',
      icon: 'none'
    })
    return
  }

  try {
    isWechatLogging.value = true

    // 获取用户信息（必须在点击事件中直接调用）
    const userProfile = await uni.getUserProfile({
      desc: '用于完善用户资料'
    })

    // 获取登录code
    const { code } = await uni.login({
      provider: 'weixin'
    })
    console.log('开始微信登录');
   const res = await userStore.wechatLogin(code)
   if(res){
    handleLoginSuccess(res)
   }
   
  } catch (error) {
    console.error('微信登录失败:', error)
    // 显示具体错误信息
    uni.showToast({
      title: error.message || '微信登录失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    // 重置登录状态
    setTimeout(() => {
      isWechatLogging.value = false
    }, 2000) // 2秒内不能重复点击
  }
}
</script>

<style lang="scss">
.login-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow: hidden;
  
  .logo {
    flex: 1;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    
    image {
      width: 100%;
      height: 90%;
      object-fit: cover;
    }
    
    .welcome-text {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 20rpx;
      
      text {
        color: #fff;
        font-size: 48rpx;
        font-weight: bold;
        text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.5);
        white-space: nowrap;
      }
      
      .line1 {
        font-size: 56rpx;
      }
      
      .line2 {
        font-size: 64rpx;
      }
    }
  }
  
  .login-tab {
    display: flex;
    padding: 20rpx 60rpx 0;
    
    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #999;
      padding: 20rpx 0;
      border-bottom: 4rpx solid transparent;
      
      &.active {
        color: #007AFF;
        border-bottom-color: #007AFF;
      }
    }
  }
  
  .login-form {
    padding: 40rpx 60rpx;
    background-color: #fff;
    
    .form-item {
      margin-bottom: 30rpx;
      
      input {
        width: 100%;
        height: 88rpx;
        padding: 0 30rpx;
        border: 2rpx solid #eee;
        border-radius: 44rpx;
        font-size: 28rpx;
        
        &:focus {
          border-color: #007AFF;
        }
      }
      
      &.sms-form-item {
        display: flex;
        align-items: center;
        
        input {
          flex: 1;
        }
        
        .sms-btn {
          width: 200rpx;
          height: 88rpx;
          line-height: 88rpx;
          margin-left: 20rpx;
          font-size: 24rpx;
          color: #fff;
          background-color: #007AFF;
          border-radius: 44rpx;
          text-align: center;
          
          &[disabled] {
            background-color: #ccc;
          }
        }
      }
    }
    
    .btn-group {
      display: flex;
      justify-content: space-between;
      margin: 40rpx 0;
      
      button {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        
        &.btn-login {
          background-color: #007AFF;
          color: #fff;
        }
        
        &.btn-register {
          background-color: #fff;
          color: #007AFF;
          border: 2rpx solid #007AFF;
          margin-left: 20rpx;
        }
      }
    }
    
    .wechat-login {
      .divider {
        position: relative;
        text-align: center;
        margin: 30rpx 0;
        
        &::before,
        &::after {
          content: '';
          position: absolute;
          top: 50%;
          width: 30%;
          height: 2rpx;
          background-color: #eee;
        }
        
        &::before {
          left: 0;
        }
        
        &::after {
          right: 0;
        }
        
        text {
          display: inline-block;
          padding: 0 20rpx;
          color: #999;
          font-size: 24rpx;
        }
      }
      
      .btn-wechat {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 88rpx;
        background-color: #07C160;
        border-radius: 44rpx;
        color: #fff;
        font-size: 32rpx;
        
        image {
          width: 40rpx;
          height: 40rpx;
          margin-right: 10rpx;
        }
      }
    }
  }
}
</style>
